<template>
  <div id="userLayout">
    <div class="loginTitle">
      <img src="@/assets/common/logo.png" alt="" />
      <div class="loginText">{{ $GIN_VUE_ADMIN.appName }}</div>
    </div>
    <div class="login_panel">
      <div class="login_panel_form">
        <div class="login_panel_form_title">
          <p class="login_panel_form_title_p">用户登陆</p>
        </div>
        <el-form ref="loginForm" :model="loginFormData" :rules="rules" :validate-on-rule-change="false"
          @keyup.enter="submitForm">
          <el-form-item prop="username">
            <el-input v-model.trim="loginFormData.username" placeholder="请输入用户名" class="inputDeep">
              <template #prefix>
                <span class="input-icon">
                  <img src="../../assets/img/login/username.png" alt="">
                </span>
              </template>
              <template #suffix>
                <span class="input-icon password">
                  <el-icon :size="20">
                    <CircleClose @click="loginFormData.username = ''" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="loginFormData.password" :type="lock === 'lock' ? 'password' : 'text'"
              placeholder="请输入密码" class="inputDeep">
              <template #prefix>
                <span class="input-icon">
                  <img src="../../assets/img/login/password.png" alt="">
                </span>
              </template>
              <template #suffix>
                <span class="input-icon password">
                  <el-icon :size="20">
                    <component :is="lock" @click="changeLock" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha" v-if="picPath">
            <div class="vPicBox">
              <el-input v-model.trim="loginFormData.captcha" placeholder="请输入验证码" style="width: 60%" />
              <div class="vPic">
                <img :src="picPath" alt="请输入验证码" @click="getCaptchaCode()" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" :loading="btnLoading" v-prevent-repeat-click
              style="width: 98%; height: 34px !important; margin: 40px auto 0px auto" @click="submitForm">
              登 录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- <div class="login_panel_foot">
      <div class="copyright">养老服务管理系统</div>
    </div> -->

    <pub-dialog v-if="dialogFormVisibleUpdatePWD" title="修改密码" v-model:visible="dialogFormVisibleUpdatePWD" width="600px"
      :showClose="pwdInfo.required" @close="close">
      <updatepwd ref="ruleFormRef" :pwdInfo="pwdInfo" @close="close" @submitForm="submitFormPW" />
    </pub-dialog>
  </div>
</template>

<script setup>
import { sessionMemory } from '@/utils/sessionMemory'
import updatepwd from './updatepwd.vue'
import { check_password, get_captcha, update_pwd, login } from '@/api/api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import { Sm4encrypt } from '@/utils/encryption.js'
import { Search } from '@element-plus/icons-vue'
const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length === 0) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPasswordRule = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

const dialogFormVisibleUpdatePWD = ref(false)
const pwdInfo = reactive({
  name: '',
  msg: '',
  required: false
})

// 登录相关操作
const isTopMenus = ref(window.sessionStorage.getItem('isTopMenus') || 1)
const loginForm = ref(null)
const picPath = ref('')
const lock = ref('lock')
const btnLoading = ref(false)
const changeLock = () => {
  lock.value = lock.value === 'lock' ? 'unlock' : 'lock'
}
const captchaKey = ref('')
const getCaptchaCode = async () => {
  let res = await get_captcha()
  if (res.succeed) {
    if (res.captchaEnabled == 1) {
      ; (picPath.value = res.captchaImageBase64),
        (captchaKey.value = res.captchaKey)
    } else {
      picPath.value = ''
    }
  }
  btnLoading.value = false
}
const userStore = useUserStore()
const state = reactive({
  result: {}
})
const loginInfo = ref({})
const loginFormData = reactive({
  username: '',
  password: '',
  captcha: ''
})
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPasswordRule, trigger: 'blur' }],
  getCaptcha: [
    {
      message: '验证码格式不正确',
      trigger: 'blur'
    }
  ]
})

const getCheckPassword = async () => {
  let res = await check_password()
  // 强制修改密码
  if (res.status === 1001 || res.status === 1002 || res.status === 1005) {
    pwdInfo.required = true
    pwdInfo.msg = res.msg
    dialogFormVisibleUpdatePWD.value = true
    return false
  } else if (res.status === 1003 || res.status === 1004) {
    // 建议修改密码
    pwdInfo.required = false
    pwdInfo.msg = res.msg
    dialogFormVisibleUpdatePWD.value = true
    return false
  } else {
    return true
  }
}

const loginHandle = async () => {
  pwdInfo.name = loginFormData.username
  let params = {}
  params.username = loginFormData.username
  params.password = Sm4encrypt(loginFormData.password)
  params.captchaKey = captchaKey.value
  params.captcha = loginFormData.captcha
  return await login(params)
}

const submitForm = () => {
  loginForm.value.validate(async v => {
    if (v) {
      btnLoading.value = true
      const res = await loginHandle()
      if (res.succeed) {
        loginInfo.value = res
        //存储密钥（加密）
        userStore.setToken(res.data.token)
        let checkStatus = await getCheckPassword()
        if (checkStatus) {
          await userStore.toLogin(res)
          btnLoading.value = false
        }
      } else {
        // 登录失败
        getCaptchaCode()
        btnLoading.value = false
      }
    }
  })
}

const close = async () => {
  if (!pwdInfo.required) {
    userStore.toLogin(loginInfo.value)
  } else {
    userStore.ClearStorage()
    getCaptchaCode()
  }
  dialogFormVisibleUpdatePWD.value = false
}

// 提交修改密码
const submitFormPW = data => {
  const updateDate = {
    originalPassword: '',
    newPassword: ''
  }
  updateDate.originalPassword = Sm4encrypt(data.originalPassword)
  updateDate.newPassword = Sm4encrypt(data.newPassword)
  update_pwd(updateDate)
    .then(result => {
      if (result.succeed) {
        ElMessage.success(result.msg)
        userStore.LoginOut()
        dialogFormVisibleUpdatePWD.value = false
        btnLoading.value = false
      }
    })
    .catch(() => { })
}

// 获取验证码
getCaptchaCode()
</script>

<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  height: 34px !important;
  padding: 1px 2px;
}

#userLayout {
  margin: 0;
  padding: 0;
  background-image: url('@/assets/img/login/login_bg.jpg');
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
  position: relative;

  .loginTitle {
    position: absolute;
    left: 50px;
    top: 30px;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      width: 65px;
      height: 63px;
      margin-right: 20px;
    }

    .loginText {
      color: #fff;
      font-size: 35px;
      letter-spacing: 3px;
    }
  }

  .input-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-right: 6px;
    padding-top: 4px;
    width: 14px;

    img {
      width: 100%;
    }
  }

  .password {
    cursor: pointer;
  }

  // 媒体查询
  @media screen and (max-width: 1440px) {
    .login_panel {
      transform: scale(0.92);
      position: absolute;
      top: 30%;
      right: 11%;
      // background-color: rgba(255, 255, 255, .8);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;

      .login_panel_form {
        width: 420px;
        background-color: #fff;
        padding: 40px 40px 40px 40px;
        border-radius: 10px;
        box-shadow: 2px 3px 7px rgba(0, 0, 0, 0.2);

        .login_panel_form_title {
          display: flex;
          align-items: center;
          margin: 30px 0;

          .login_panel_form_title_logo {
            width: 90px;
            height: 72px;
          }

          .login_panel_form_title_p {
            font-size: 20px;
            color: #409eff;
            font-weight: bold; // padding-left: 20px;
          }
        }

        .vPicBox {
          display: flex;
          justify-content: space-between;
          width: 100%;
        }

        .vPic {
          width: 33%;
          height: 38px;
          background: #ccc;

          img {
            width: 100%;
            height: 100%;
            vertical-align: middle;
          }
        }
      }
    }
  }

  @media screen and (min-width: 1441px) {
    .login_panel {
      position: absolute;
      top: 30%;
      right: 15%;
      // background-color: rgba(255, 255, 255, .8);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;

      .login_panel_form {
        width: 420px;
        background-color: #fff;
        padding: 40px 40px 40px 40px;
        border-radius: 10px;
        box-shadow: 2px 3px 7px rgba(0, 0, 0, 0.2);

        .login_panel_form_title {
          display: flex;
          align-items: center;
          margin: 30px 0;

          .login_panel_form_title_logo {
            width: 90px;
            height: 72px;
          }

          .login_panel_form_title_p {
            font-size: 20px;
            color: #409eff;
            font-weight: bold; // padding-left: 20px;
          }
        }

        .vPicBox {
          display: flex;
          justify-content: space-between;
          width: 100%;
        }

        .vPic {
          width: 33%;
          height: 38px;
          background: #ccc;

          img {
            width: 100%;
            height: 100%;
            vertical-align: middle;
          }
        }
      }
    }
  }

  //   @media screen and (min-width: 601px) and (max-width: 990px) {
  //   }

  .login_panel_foot {
    position: fixed;
    bottom: 80px;
    left: 50%;
    color: #fff;
    transform: translateX(-50%);

    .copyright {
      font-size: 20px;
    }
  }
}

//小屏幕不显示右侧，将登录框居中
@media (max-width: 750px) {
  .login_panel {
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
  }

  .login_panel_form {
    width: 100%;
  }
}

.inputDeep {
  :deep(.el-input__wrapper) {
    box-shadow: 0px 0px 0px 0px var(--el-input-border-color, var(--el-border-color)) inset;
    border-radius: 0px;
    border-bottom: 1px solid #dedfe0;
  }

}

:deep(.el-form-item.is-error .el-input__wrapper:hover) {
  box-shadow: 0px 0px 0px 0px var(--el-input-border-color, var(--el-border-color)) inset;
  border-radius: 0px;
  border-bottom: 1px solid #f56c6c;
}
:deep(.el-form-item.is-error .el-input__wrapper.is-focus) {
  box-shadow: 0px 0px 0px 0px var(--el-input-border-color, var(--el-border-color)) inset!important;
  border-radius: 0px;
  border-bottom: 1px solid #f56c6c;
}
</style>
